<?php
declare(strict_types=1);

namespace support;

use Illuminate\Database\Events\QueryExecuted;
use Webman\Bootstrap;

class SqlDebug implements Bootstrap
{
    public static function start($worker)
    {
        Db::connection()->listen(function (QueryExecuted $queryExecuted){
            //if(env('APP_ENV')!='production') return;
            if (isset($queryExecuted->sql) and  $queryExecuted->sql !== "select 1")
            {
                $query = $queryExecuted->sql;
                $bindings = $queryExecuted->bindings;
                $time = $queryExecuted->time;
                foreach ($bindings as $bind){
                    $query = preg_replace('/\?/', (is_numeric($bind) ? $bind : '\'' . $bind . '\''), $query, 1); // 将SQL中的?替换为实际的值
                }
                $slow = $time> 1000 ? 'slow_query' : '';
                $info = "query:{$query} -- time:{$slow} {$time}ms";
                Log::channel('sql_log')->info($info);
            }
        });

    }
}